const {
  banners,
  menus,
  list,
  userList,
  tabList
} = require('./mock')
const bodyParser = require('body-parser')
const OSS = require('ali-oss')
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();
// 引入 
const AlipaySdk = require('alipay-sdk').default;
// TypeScript，可以使用 import AlipaySdk from 'alipay-sdk';
// 普通公钥模式
const alipaySdk = new AlipaySdk({
  appId: '2021000119601763',
  privateKey: `MIIEowIBAAKCAQEAw8n+AicnWKCsuW0IaBaWBBU07cMuBLvDPG9AXjSOwIcEH9udgbwvLhYL2FNVL5icv9Dd/VxDBfh6ruNqovhatq1lX8psa32+MiuJbfVqysoxnuGboV9aXfl8XDcrrzW42JVkTzfy73PC6iOeccYH9YFzL8jJdQN4Iov9swAGVA7n87TkI/I+NhI/hz3bC7AXYjF9Ozi+/pXRel/YsptfmmHteSuQ9R1N7q1pQceuF5fSPh3eVEKn94OvO1fzmQdR0uBu3c0RFhWD1WaINsKSsSP0vihDUwNJK74XoTrbZVnvOhdpKTCH8sNqM8ST+M3UZ+WO/Ia1Q1imS1dMG6jM+QIDAQABAoIBAHeR7Kaz8ruVpOa5R+EJqiRkLyblhD0vzlQiPVVLE8NQsZwjK1YH72hd3m4GtoeS1GfwzyHkLqp+za3xBTbyJbRawQZ3QS+EY5uQKyYUM1wVj6hQcBNlgHLT4rcOmocub+0Vj2Ux7hN+xxLnHeSt5D5zCD2uihoEPGIczJt88GB0hi+JqZitGWs+X0voQouPusAfW4F/qN+mgcnxGrnQ/5raWTFOlLPw/uxNdsZTdQ4fjfGTpOkK859uDN9rjxcvacWMRS4QFqg7UZuS1DQ0cKm6jG4PPBZqPf+4fyLQjZYyssbdQ5lxrO9bO8Bw1Pqza+nfUkN5S5Xf2B5MM4D1Y4ECgYEA/2QpVl31YFaKqDVuF6pdExGK8QIuqbOZmSBa5g0+YY9v0QEGJl61HzHfooHVGlrXa/V6+dL1MLFDD6SvWyVjfSIXSJ4shNQ2L7yBdmd/ZTTYMLNEfaIedJCvAgxI2UfwstsDO3V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OZZDiGksw77FDd6TkvCLoS8cV8gGJ57BiQqa3Rqjro6/jvc7ByV1fOSxyXIMyuWQIDAQAB`,
  // 必须改一下网关
  gateway: 'https://openapi.alipaydev.com/gateway.do'
});

module.exports = (app) => {
  app.use(bodyParser.json())
  app.get('/api/banners', (req, res) => res.send({
    code: 200,
    data: banners,
    message: 'ok'
  }))
  app.get('/api/menus', (req, res) => res.send({
    code: 200,
    data: menus,
    message: 'ok'
  }))
  app.get('/api/list', (req, res) => {
    const {
      pageSize = 10, pageCode = 1
    } = req.query;

    if (pageSize * (pageCode - 1) >= list.length) {
      res.send({
        code: 400,
        message: '没有更多数据了'
      });
      return;
    }
    res.send({
      code: 200,
      data: list.slice((pageCode - 1) * pageSize, pageCode * pageSize),
      message: 'ok'
    })

  })
  app.get('/api/list/:id', (req, res) => {
    // 获取动态路由参数
    const {
      id
    } = req.params;
    let data = []
    // 拼接tab 二级数据
    tabList.forEach(v => {
      data = data.concat(v.children)
    })
    // 拼接首页
    data = data.concat(list)
    // 查找数据  通过id
    const item = data.find(v => v.id === id);

    // const item1 = tabList.find(v => v.id === id);

    if (item) {
      res.send({
        code: 200,
        data: item,
        message: 'ok'
      })
    } else {
      res.send({
        code: 400,
        message: '商品已经下架～～～, 3s之后返回首页'
      })
    }
  })
  // 支付接口
  app.post('/api/pay', async (req, res) => {
    const {
      id,
      title,
      totalPrice
    } = req.body
    const bizContent = {
      out_trade_no: id,
      total_amount: totalPrice,
      subject: title
    }
    // 支付页面接口，返回支付链接，交由用户打开，会跳转至支付宝网站
    const result = await alipaySdk.pageExec('alipay.trade.wap.pay', {
      // 请求方式
      method: 'GET',
      // 参数
      bizContent,
      // 支付成功回调地址
      returnUrl: 'https://www.taobao.com'
    });

    res.send({
      code: 200,
      data: result
    })
  })
  // 登录接口
  app.post('/api/login', (req, res) => {
    // 获取用户名和密码
    const {
      username,
      password
    } = req.body;
    // 查找
    const user = userList.find(v => v.username === username && v.password === password)
    // 判断
    if (user) {
      // 存在
      res.send({
        code: 200,
        message: "登录成功",
        data: {
          nickname: user.nickname,
          avator: user.avator,
          username: user.username,
          id: user.id
        }
      })
    } else {
      // 不存在
      res.send({
        code: 400,
        message: '账户密码错误'
      })
    }
  })

  // tab 接口
  app.get('/api/tab', (req, res) => {
    res.send({
      code: 200,
      data: tabList
    })
  })

  // 上传接口
  app.post('/api/upload', multipartMiddleware ,  async (req, res) => {
    const { name, path } = req.files.file
    const client = new OSS({
      // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
      region: 'oss-cn-beijing',
      // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
      accessKeyId: 'LTAI5t5oeRDzCfHcoiCsYY39',
      accessKeySecret: 'vL1dqVztkcX5lrVtOHgu51ywyVMFtL',
      // 填写Bucket名称。
      bucket: 'yhj-2011a',
    });

    try {
      // 填写OSS文件完整路径和本地文件的完整路径。OSS文件完整路径中不能包含Bucket名称。
      // 如果本地文件的完整路径中未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
      const result = await client.put(name,path);
      res.send({
        code: 200,
        data: result
      })
      console.log(result);
    } catch (e) {
      console.log(e);
      res.send({
        code: 400,
        error: e
      })
    }
  })

  // 搜索接口
  app.get('/api/search', (req, res) => {
    const { value } = req.query;
    if(value) {
      res.send({
        code: 200,
        data: list.filter(v => JSON.stringify(v).includes(value) )
      })
    } else {
      res.send({
        code: 200,
        data: list
      })
    }
  })  
}